define(function(require, exports){
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var grid  = require('@base/highGrid');
	var util = require('util');

	var Customer = grid.base.extend({
		init: function(config){
			config = pubjs.conf(0, config, {
					url: 'user/list',
					urlManualDeny: 'user/manualDeny',
					reqType: 'websocket',
					cols: [
						// {name: '_id', text: LANG('ID'), sort: true},
						{name: 'UserId', text: LANG('ID'), sort: true, width: 50, align: 'center'},
						{name:'Name', text:LANG('客户名称'), type:'index', width: 300, render:"reanderStatus"},
						{name:'Type', text:LANG('类型'), render:'renderType', align: 'center'},
						{name:'CategoryId',text:LANG('版本'),render:'renderCategory', align: 'center'},
						{name:'CostRateTmp', text:LANG('溢价'), render:'renderCostRateTmp', 'width': 47, align: 'center'}
					],
					subs: ['admin_direct', 'admin_cost'],
					metrics:[
						// {name:'Remain', text:LANG('余额'), render:'renderRemain'},
						// {name:'AllowAdCredit', text:LANG('可用额度'), render:'renderAllowAdCredit'},
						// 使用redis的余额作为显示，方便排序，但是存在延时因为用户金额定时任务5分钟更新一次
						{name:'RedisRestAmount', text:LANG('余额'), render:'renderRemain', sort: true},
						{name:'RedisAllowAdCredit', text:LANG('可用额度'), render:'renderAllowAdCredit', sort: true},
						{name:'YesterdayCost', text:LANG('昨日消费'), render:'renderYesterdayCost', sort: true},
						{name:'InvoiceStatus', text:LANG('发票信息'), render:'renderInvoice', align: 'center'},
						{name:'Time', text:LANG('登录信息'), render:'renderLoginInfo', align: 'center'}
					],
					param: {
						order: 'CreateTime|-1'
					},
					key: 'UserId',
					subFilter: 'subFilter',
					hasSelect: false,
					hasTab: false,
					hasSwitch: false,
					hasAmount: false,
					hasSearch: false,
					hasExport: true,
					hasRefresh: true,
					hasMenu: true,
					gridName: 'user'
				}
			);

			this.Super('init', arguments);
		},
		renderType: function(i, val){
			var data = [0, LANG('代理'), LANG('直客'), LANG('员工'), LANG('超级管理员')];
			var value = (val != null) ? data[+val]: '-';
			return value;
		},
		renderLoginInfo: function(i,val,row,con){
			var html = $([
					'<div>',
						LANG("最近登录时间：%1", util.date("Y-m-d H:i:s", row.UpdateTime)),
					'</div>',
					'<div>',
						LANG("帐号添加时间：%1", util.date("Y-m-d H:i:s", row.CreateTime)),
					'</div>'
				].join(''));
			return html;
		},
		//渲染溢价
		renderCostRateTmp: function(i, val, row, con){
			var value = +row.Finance.CostRateTmp || 0;
			return (value ? value + '%' : '-');
		},
		renderCategory: function(i, val, row, con){
			var type = row.ExchangeInfo.CategoryId;
			switch (type){
				case 1: return LANG('有产品版');
				case 2: return LANG('无产品版');
				default:
					return LANG('未知');
			}
		},
		//格式化百分比
		formatRate: function(rate, size){
			if (isNaN(+size)){ size = 3; }
			rate = util.round0(rate * 100, size);
			return util.numberFormat(rate) + '%';
		},
		//余额
		renderRemain: function(i, val, row, con){
			// var data = row.Finance.Cost.Remain;
			var data = row.Finance.Cost.RedisRestAmount;
			data = this.formatRest(data);
			if(parseFloat(data) < 0){
				// 余额为负数时红色高亮
				data = '<span class="red">'+data+'</span>';
			}
			return data;
		},
		//可用额度
		renderAllowAdCredit: function(i, val, row, con){
			// var AllowAdCredit = row.Finance.Credit.AllowAdCredit,
			// 	Credit = AllowAdCredit,
			// 	Remain = row.Finance.Cost.Remain;
			// if(Remain < 0){
			// 	AllowAdCredit = AllowAdCredit + Remain;
			// 	AllowAdCredit = AllowAdCredit < 0 ? 0 : AllowAdCredit;
			// }
			var AllowAdCredit = row.Finance.Credit.AllowAdCredit;
			var RedisAllowAdCredit = this.formatRest(row.Finance.Credit.RedisAllowAdCredit);
			return '<span title="'+ AllowAdCredit + '">' + LANG("￥") + RedisAllowAdCredit + '</span>';
		},
		renderInvoice:function(i, val, row, con){
			var status = row.Finance.Invoice.Status;
			return {
				'1':LANG('资料不全'),
				'2':LANG('待审核'),
				'3':LANG('已通过'),
				'4':LANG('已拒绝')
			}[status]||LANG('资料不全');
		},
		renderYesterdayCost: function(i, val, row, con){
			return this.formatRest(row.Finance.Cost.YesterdayCost);
		},
		//格式化金额
		formatRest: function(val){
			val = util.round0(val,2);
			val = util.numberFormat(val);
			return val;
		},
		reanderStatus: function(i, val, row, con, tr){
			val = LANG(val) || '';
			var manualDeny = +row.ManualDeny;
			var status = +row.Status||1;
			// 系统判断原因
			var systemDeny = row.SystemDeny || {};
			var reason = '';
			var reason1 = systemDeny.contract  && LANG('合同到期') || '';
			var reason2 = systemDeny.arrears  && LANG('账户欠费') || '';
			var reason3 = !systemDeny.contract && !systemDeny.arrears && LANG('正常') || '';
			reason = reason1 + (reason1&&reason2&&'、'||'') + reason2 + reason3;
			var status_map = {
				'1': {'text': LANG('系统启用'), 'icon': 'running'},
				'2': {'text': LANG('系统禁用'), 'icon': 'pause'}
			};
			var manualDeny_map = {
				'1': {'text': LANG('人工启用'), 'icon': 'manual_start'},
				'2': {'text': LANG('人工禁用'), 'icon': 'manual_pause'}
			};
			var returnValue;
			var text;
			if(manualDeny === 1 || manualDeny === 2){
				text = manualDeny_map[status].text;
				var manualIcon = manualDeny_map[manualDeny].icon;
				var manualReason = (row.DenyInfo && row.DenyInfo['0']) || '';    //手工启用或控制的备注
				returnValue =$([
								'<div class="uk-text-truncate tl fl" title="'+val+'">',
									'<i title="'+LANG('点击取消人工控制')+'" data-text="'+text+'" class="'+manualIcon+' mr5 manual" data-id="'+ row.UserId +'" data-status="'+status+'" data-reason="'+ reason +'" data-manual="'+ manualReason +'" data-type="manual"></i>',
								'</div>'
							].join(''));
			}else if(manualDeny === 3 || !manualDeny){
				text = status_map[status].text;
				var statusIcon = status_map[status].icon;
				returnValue =$([
								'<div class="uk-text-truncate tl fl" title="'+val+'">',
									'<i title="'+text+'" data-text="'+text+'" class="'+statusIcon+' mr5" data-status="'+status+'" data-reason="'+ reason +'" data-type="system"></i>',
								'</div>'
							].join(''));
			}

			var className = (+row.ShowAgent) ? "uk-icon-user mr5 text-muted" : " ";
			var title = LANG("所属公司ID：") + row.CreateUserId + '\n' +
						LANG("所属公司：") + row.AgentUserName +" ( "+ row.AgentEmail + " )";
			var user = $([
				'<div class="dib valign-m uk-text-truncate">',
					'<a class="valign-m" target="_self" href="javascript:void(0);">',
						'<i class="'+className+'" title="'+title+'"/>',
						val,
					'</a>',
					'<div class="emailName uk-text-truncate uk-text-muted" title="'+row.Email+'">',
						row.Email || '',
					'</div>',
				'</div>'
			].join('')).appendTo(returnValue).width(240);

			if(pubjs.routerValid('user.info')){
				user.find('a').attr('href', '#admin/customer/edit/' + row.UserId);
			}

			returnValue.outerWidth(280);

			this.uiBind(returnValue.find('.manual'),'click','eventManual');
			this.uiBind(returnValue.find('>i'),'mouseenter mouseleave','eventShowStatusTips');

			this.uiBind(returnValue.find('.emailName'), 'dblclick', function(evt, elm){
				pubjs.clipboard(returnValue);
			});

			return returnValue;




			/*var status_map = {
				'0': {'text': LANG('正常'), 'icon': 'running'},
				'1': {'text': LANG('只读'), 'icon': 'running'},
				'2': {'text': LANG('系统禁用'), 'icon': 'pause'},
				'3': {'text': LANG('手工启动'), 'icon': 'manual_start'},
				'4': {'text': LANG('手工禁用'), 'icon': 'manual_pause'}
			};

			var status = 0;
			status = this.filterStatus(+row.Status);

			var statusIcon = status_map[status].icon;
			var text = status_map[status].text;
			var reason = '';

			if(status == 2){
				reason = LANG('合同到期');
			}else{
				reason = LANG('正常');
			}

			var returnValue = {};
			//判定是否人工禁止操作，渲染不同
			//人工操作，增加多class增加.manual,并绑定click事件
			if(status == 3 || status == 4){
				var manualReason = row.DenyInfo['4'] || '';
				returnValue =$([
								'<div class="uk-text-truncate tl fl" title="'+val+'">',
									'<i title="'+text+'" class="'+statusIcon+' mr5 manual" data-id="'+ row._id +'" data-status="'+status+'" data-reason="'+ reason +'" data-manual="'+ manualReason +'"></i>',
									val,
								'</div>'
							].join('')).width(con.width-20);
			}else{
				returnValue =$([
								'<div class="uk-text-truncate tl fl" title="'+val+'">',
									'<i title="'+text+'" class="'+statusIcon+' mr5" data-status="'+status+'" data-reason="'+ reason +'"></i>',
									val,
								'</div>'
							].join('')).width(con.width-20);
			}

			this.uiBind(returnValue.find('.manual'),'click','eventManual');
			this.uiBind(returnValue.find('i'),'mouseenter mouseleave','eventShowStatusTips');
			return returnValue;*/
		},
		// 鼠标移入移出事件，控制提示框显隐
		eventShowStatusTips: function(ev, elm){
			var tip  = this.get('StatusTips');
			switch (ev.type){
				case 'mouseenter':
					elm = $(elm);
					var statusTips = elm.attr("data-text");
					var reasonTips = elm.attr("data-reason");
					// var status = elm.attr("data-status");
					var type = elm.attr("data-type");
					var html = [
						'<p>',
							LANG('当前状态：')+statusTips,
						'</p>',
						'<p>',
							LANG('系统判断：')+reasonTips,
						'</p>'
					];
					if(type == 'manual'){
						var manualReason = elm.attr("data-manual");
						if(util.isString(manualReason)){
							html.push('<p>'+LANG('备注：')+manualReason+'</p>');
						}
					}
					html = $(html.join(''));
					if (!tip){
						tip = this.createAsync('StatusTips', '@base/tip.base', {
							'width': 150,
							'pos': 'tm',
							'anchor': elm,
							'autoHide': 1,
							'outerHide': 1
						},function(mod){
							mod.setData(html);
							mod.show();
						});
					}else{
						tip.update({'anchor': elm});
						tip.setData(html);
						tip.show();
					}
				break;
				case 'mouseleave':
					if (tip){ tip.hide(); }
				break;
			}
			return false;
		},
		//状态图标点击事件
		//未完成接口，点击后打印出信息
		eventManual: function(ev,elm){
			var self = this;
			var el = $(elm);
			var url = this.getConfig('urlManualDeny');
			var id = el.attr("data-id");
			var data = this.getData(+id);
			pubjs.confirm(LANG('真的要取消人工控制账户 (%1) 吗？', data.Name), function(isOK){
				if(isOK){
					var param = {
						'_id': data.UserId,
						'Status': 3
					};
					pubjs.mc.send(url, param, self.afterToggleStatus.bind(self));
				}
			});
		},
		// 修改人工状态后，回调刷新列表
		afterToggleStatus: function(err, data){
			if (err){
				pubjs.error(err);
				return false;
			}
			this.load();
		},

		//subFilter未写
		subFilter: function(subs, data){
			var trade = data.Type;
			// 代理才有直客的子表格
			util.each(subs, function(sub){
				if (sub.type === 'admin_direct'){
					sub.iconBtn.toggle(trade == 1);
				}
			});
		}
		/*
		,filterStatus: function(status){
			//0正常 1只读 2系统禁用 3手工启动 4手工禁用

			var map = {
				NORMAL: 1 << 0,
				SYS: 1 << 1,
				MANSTATUS: 1 << 2,
				MANUAL: 1<< 3,
				AUTO: 1 << 4
			}

			var sys = status & map.SYS;
			var manual = status & map.MANUAL;
			var manStatus = status & map.MANSTATUS;
			var auto = status & map.AUTO;
			var normal = status & map.NORMAL;

			var result = 0;
			//如果自动禁止，即因父代被手动禁止导致下级被禁止
			if(auto){
				return result = 4;   //手动禁止
			}
			if(manual){
				if(manStatus == 0){
					return result = 3;	//手工启动
				}else{
					return result = 4;	//手工禁止
				}
			}
			if(sys){
				return result = 2;
			}

			//前面都不匹配 最后返回 正常或只读
			return result = normal;

		}*/
	});
	exports.base = Customer;

	// 广告位汇总报表的客户子表格
	var Spot = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'user/subList',
					param: {
						'IsDeleted': false
						,'Type': 0
						,'order': 'impressions|-1,clicks|-1'
						,'get_all_info': 1
					},
					cols:[
						{name:'UserId',text:LANG("ID"), sort: true}
						,{name:"Name",text: LANG("名称"),render:"renderName",width:210}
					],
					default_metrics: pubjs.config('metricsGroup/campaign/metrics'),
					// 在竞价组中有出价
					tab: pubjs.config('metricsGroup/campaign/tabs'),
					reqType: 'websocket',
					hasSwitch: false,
					gridName: 'spot_customer',
					exportParam: 'user/subList',
					hasExport: false,
					subs: ['campaign'],
					subField: 'spot'
				}
			);
			this.Super('init', arguments);
		},
		renderName: function(i, val, data, con){
			val = val || '-';
			return $('<div class="uk-text-truncate tl fl" title="'+val+'">'+val+'</div>').width(con.width-20);
		}
	});
	exports.spot = Spot;

});